package com.wsdcd.zlg.controller;

import com.wsdcd.zlg.core.exception.ERPException;
import com.wsdcd.zlg.model.entity.Customer;
import com.wsdcd.zlg.model.service.CustomerService;
import com.wsdcd.zlg.util.AjaxObject;
import com.wsdcd.zlg.util.PageParameter;
import com.wsdcd.zlg.util.PagerUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import java.util.Arrays;
import java.util.List;

@AllArgsConstructor
@Controller
@RequestMapping("/customer")
public class CustomerController {
	private final CustomerService customerService;

	@RequestMapping("list")
	public String customerList() {
		return "customer/list";
	}

	@ResponseBody
	@RequestMapping("customerName")
	public List<Customer> userList(){
		return customerService.select();
	}

	@ResponseBody
	@RequestMapping("lists")
	public PagerUtil<Customer> orderLists(int page, int limit,String searchType,String searchValue) {
		if(searchValue != null){
			searchValue = searchValue.trim();
		}
		PageParameter pageParameter = new PageParameter(page,limit,searchType,searchValue);
		return customerService.selectByPage(pageParameter);
	}
	
	@RequestMapping("add")
	public String add() {
		return "customer/add";
	}

	@ResponseBody
	@RequestMapping("adds")
	public AjaxObject adds(Customer customer) {
		try {
			customerService.insert(customer);
			String msg = "添加成功";
			return new AjaxObject(1, msg);
		} catch (ERPException e) {
			String msg = e.getMessage();
			return new AjaxObject(0, msg);
		}
	}

	@RequestMapping("update")
	public String update(String customerId, Model model) {
		Customer customer = customerService.selectByCustomerId(customerId);
		model.addAttribute("updateCustomer", customer);
		return "customer/update";
	}

	@ResponseBody
	@RequestMapping("updates")
	public AjaxObject updates(Customer customer) {
		try {
			customerService.update(customer);
			String msg = "修改成功";
			return new AjaxObject(1, msg);
		} catch (ERPException e) {
			String msg = e.getMessage();
			return new AjaxObject(0, msg);
		}
	}

	@ResponseBody
	@RequestMapping("deleteAll")
	public AjaxObject deleteAll(String customerIds)
			throws ServletException {
		if(customerIds == null || customerIds.trim().equals("")){
			String msg = "删除失败，请传递数据";
			return new AjaxObject(0, msg);
		}
		String[] arr = customerIds.split(",");
		int[] array = Arrays.stream(arr).mapToInt(Integer::parseInt).toArray();
		try {
			customerService.deleteAll(array);
			String msg = "删除成功";
			return new AjaxObject(1, msg);
		} catch (ERPException e) {
			String msg = e.getMessage();
			return new AjaxObject(0, msg);
		}
	}
	
}
